package com.shd.edanpei.ui.activity;

import com.shd.edanpei.base.BasePresenterImpl;
import com.shd.edanpei.base.network.api.ApiCreator;
import com.shd.edanpei.base.network.model.NoDataResponse;
import com.shd.edanpei.base.network.rx.BaseObserver;
import com.shd.edanpei.base.network.rx.RxTransformer;
import com.shd.edanpei.bean.PayServiceModel;
import com.shd.edanpei.presenter.contract.PayServiceContract;

import java.io.File;

import io.reactivex.android.schedulers.AndroidSchedulers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * Created by mc on 2018/9/30.
 * yang-wen-wen
 */

public class PayServicePresenter extends BasePresenterImpl<PayServiceContract.PayServiceIView>
        implements PayServiceContract.PayServiceIPresenter {

    public PayServicePresenter(PayServiceContract.PayServiceIView mView) {
        super(mView);
    }

    @Override
    public void getData(int orderID) {
        ApiCreator.getApi().getPayServiceInfo(orderID)
                .compose(RxTransformer.<PayServiceModel>errorHandle())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<PayServiceModel>() {
                    @Override
                    protected void onSuccess(PayServiceModel data) {
                        mBaseIView.setData(data);
                    }
                });
    }

    @Override
    public void upload(String path, final int orderID) {
        ApiCreator.getApi().uploadPicture(createFileBody(path), createStrBody("1"))
                .compose(RxTransformer.<String>errorHandle())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<String>() {
                    @Override
                    protected void onSuccess(String data) {
                        submit(data, orderID);
                    }
                });
    }

    private void submit(String url, int orderID) {
        ApiCreator.getApi().submitServiceChargeCert(orderID, url)
                .compose(RxTransformer.<NoDataResponse>errorHandle())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<NoDataResponse>() {
                    @Override
                    protected void onSuccess(NoDataResponse data) {

                    }
                });
    }

    private MultipartBody.Part createFileBody(final String pic) {
        File file = new File(pic);
        RequestBody requestBody = RequestBody.create(MediaType.parse("image/png"), file);
        return MultipartBody.Part.createFormData("file", file.getName(), requestBody);
    }

    private RequestBody createStrBody(final String value) {
        return RequestBody.create(MediaType.parse("text/plain"), value);
    }
}
